// pages/law/search/index.js

import util from '../../utils/util';
var WxParse = require('../../wxParse/wxParse.js');

function _pretiffySerchResult(_content){
  // return _content;
  _content = _content.replace(/^([^class]|)\="law-link">/, "");
  _content = _content.replace(/<a.+?>|<div.+?>|<p.+?>/g, "");
  _content = _content.replace(/<\/a>/g, "");
  _content = _content.replace(/<\/p>|<\/div>/g, "<br>");

  _content = _content.replace(/<a.+?|<div.+?|<p.+?/g, "");

  return _content;
}

function _getSearchContent(_search, _obj){
  wx.showToast({
    title: '加载中',
    icon: 'loading',
    duration: 10000
  });

  wx.request({
    url: `${getApp().globalData.serverHost}/wx/bd/law/search`, //仅为示例，并非真实的接口地址
    data: {
      search: _search
    },
    method: "post",
    header: {
        'content-type': 'application/json'
    },
    success: function(res) {
      wx.hideToast();
      
      var _data = res.data;
      var _title = res.data.title;
      var _content = res.data.content;
      var _list = [];

      var _titleHtml = "";
      for(var i=0; i<_title.length; i++){
        _list.push(i);
        _titleHtml += ('<a click="go" href="../detail/index/index?id='+_title[i].id+'&name='+_title[i].title+'"><div class="title">' + (!!_title[i].highlight ? _title[i].highlight.title[0] : _title[i].title) + '</div></a>');
        WxParse.wxParse('title', 'html', _titleHtml, _obj);
      }

      var _contentHtml = "";
      for(var i=0; i<_content.length; i++){
        _list.push(i);
        _contentHtml += ('<a href="../detail/index/index?id='+_content[i].id+'&name='+_content[i].title+'"><div class="title>' + _content[i].title + '</div><div class="content">' + (!!_content[i].highlight ? _pretiffySerchResult(_content[i].highlight.content[0]) : "") + '</div></a>');
        WxParse.wxParse('content', 'html', _contentHtml, _obj);
      }

      _obj.setData({
        list: _list
      })
    },
    fail: function(res){
      console.log(res);
    }
  })
}

Page({
  data:{
    search: ""
  },
  onLoad:function(options){
    var that = this;
    
    this.setData({
      search: options.search,
      searchContent: ""
    });
    
    _getSearchContent(this.data.search, this);
  },
  bindLawInput: function(_event) {
    this.setData({
      searchContent: _event.detail.value
    });
  },
  bindSearchLaw: function(_event) {
    if(!!_event.target.dataset.search){
      _getSearchContent(_event.target.dataset.search, this);
    }

    if(!!this.data.searchContent){
      _getSearchContent(this.data.searchContent, this);
      util.getOrSetHistorySearch(this.data.searchContent);
    }
  },
  wxParseTagATap: function(_event){
    wx.navigateTo({
      url: _event.currentTarget.dataset.c + "&search=" + this.data.search,
    });
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  }
})